package com.yourwork.controller;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.yourwork.model.Clientele;
import com.yourwork.model.Recharge;
import com.yourwork.service.RechargeService;
@Controller
@RequestMapping(value="/recharge")
//客户充值
public class RechargeController {
	@Autowired
	@Qualifier(value="payListService")
	private RechargeService payListService;
	//查询
	@RequestMapping(value="/select",method={RequestMethod.GET})
	public String toPayList(Model m,@RequestParam(name="page",defaultValue="0")int page,
			@RequestParam(name="size",defaultValue="10")int size,HttpSession session){
		//查充值记录表
		//返回当前页size条数据的记录存入pagePayList
		try{int count = payListService.countPayList();
		if(page<=(count/size)&&count%size!=0){page=page+0;}
		else{if(count%size==0){page=count/size-1;}
		else{page = count/size;}}
		Page<Recharge> pagePayList = payListService.queryPayList(page,size);
		List<Recharge> list = new ArrayList<Recharge>();
		for(Recharge r: pagePayList){
			list.add(r);
		}
		int maxPage = payListService.queryMaxPage(page,size);
		m.addAttribute("maxPage", maxPage);
		m.addAttribute("page", page);
		m.addAttribute("size", size);
		m.addAttribute("count", count);
		addAttribute(m, "list", list, true);
		m.addAttribute("remind", session.getAttribute("remind"));//获得提示信息
		m.addAttribute("managerNumber", session.getAttribute("managerNumber"));
		session.setAttribute("remind", "");//清空提示信息
		return "/work/pay";}catch (Exception e) {
			// TODO: handle exception
			return "/work/pay";
		}
	}
	/**
	 * 插入充值记录
	 * @param payList 表单绑定的表
	 * @param session 存值
	 * */
	@RequestMapping(value="/addrecharge",method={RequestMethod.POST})
	public String pay(@ModelAttribute(name="payList") Recharge paylist,
			HttpSession session){
		String remind = payListService.insertPayList(paylist);//添加数据返回是否添加成功
		session.setAttribute("remind", remind);//remind 存入session
		return "redirect:/recharge/select";
	}
	
	private void addAttribute(Model m,String attributeName,Object attributeValue,boolean replace){
		if(replace==true){//判断是否添加attribute
			m.addAttribute(attributeName, attributeValue);
		}else{
			if(!m.containsAttribute(attributeName)){//判断是否已经存在的attribute
				m.addAttribute(attributeName, attributeValue);
			}
		}
		}
	
}
